<?php

namespace App\B2BProject\Custom;

use Illuminate\Database\Eloquent\Builder;
use Illuminate\Database\Eloquent\Model;

class GoodsSellStatistics extends Model
{
    /**
     * 获取当前统计对象对应的商品
     *
     * @return \Illuminate\Database\Eloquent\Relations\BelongsTo
     */
    public function goods()
    {
        return $this->belongsTo('App\B2BProject\Custom\Business\Goods', 'goods_id', 'id');
    }

    /**
     * 获取当日销量数据
     *
     * @param Builder $builder
     *
     * @return int
     */
    public function scopeTodayCount(Builder $builder)
    {
        $newBuilder = $this->newBuilder($builder);

        if ($newBuilder->where('created_at', date('Y-m-d'))->count() == 0) {
            return 0;
        }

        return $builder->where('created_at', date('Y-m-d'))->pluck('amount');
    }

    /**
     * 获取当月销量
     *
     * @param Builder $builder
     *
     * @return int
     */
    public function scopeMonthCount(Builder $builder)
    {
        if ($this->newBuilder($builder)->where('created_at', '>=', date('Y-m-1'))->where('created_at', '<=',
                date('Y-m-t'))->count() == 0
        ) {
            return 0;
        }

        return $builder->where('created_at', '>=', date('Y-m-1'))->where('created_at', '<=',
            date('Y-m-t'))->sum('amount');
    }

    protected function newBuilder(Builder $builder)
    {
        return clone $builder;
    }
}
